package com.icim.rest;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.icim.common.LoadHistoryConfig;
import com.icim.rabbitmq.util.RabbitmqManager;
import com.icim.service.impl.LoadMainService;
import com.icim.util.TimeUtil;

@Controller
public class LoadErrorHistoryMainController {

	private static Logger logger = Logger
			.getLogger(LoadHistoryMainController.class);

	private final static String _OKOKOK = "OKOKOK";
	private final static String _FAIL = "FAIL";
	private final static String END_PIXEL = "\r\n";
	@Autowired
	AmqpTemplate amqpTemplate;

	@Autowired
	LoadHistoryConfig loadHistoryConfig;
	@Autowired
	RabbitmqManager rabbitmqManager;

	@RequestMapping(value = "/sendErrorMessage.do")
	public void sendErrorMessage(HttpServletRequest request,
			HttpServletResponse response) {
		try {
			String errorMessage = request.getParameter("message");
			if (errorMessage == null) {
				errorMessage = "===This is for test error message====";
			}
			rabbitmqManager.setMessage(
					loadHistoryConfig.getHistoryErrQueueName(), errorMessage);
			// amqpTemplate.convertAndSend(loadHistoryConfig.getHistoryErrQueueName(),errorMessage);

			response.setContentType("application/json");
			PrintWriter pw = response.getWriter();
			pw.write(_OKOKOK);
			pw.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	@RequestMapping(value = "/exportErrorHisQueue.do")
	public void exportMesssageToFile(HttpServletRequest request,
			HttpServletResponse response) {
		String exportFileName = null;
		String rtnMessage = null;
		try {
			exportFileName = createExportFile();
			rtnMessage = exportErrorHisQueueMessageToFile(exportFileName);

			response.setContentType("application/json");
			PrintWriter pw = response.getWriter();
			pw.write(rtnMessage);
			pw.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	private String createExportFile() {
		String exportPath = loadHistoryConfig.getExportFilePath();
		String currentTimestamp = TimeUtil.getRvTime();
		String fileName = exportPath + currentTimestamp + ".txt";
		File file = null;
		try {
			file = new File(fileName);
			if (!file.exists()) {
				file.createNewFile();
				logger.info("Create File[" + fileName + "] Successful");
			}
			return fileName;
		} catch (Exception e) {
			logger.error(e.toString());
		}
		return null;
	}

	private String exportErrorHisQueueMessageToFile(String fileName) {
		File file = new File(fileName);
		FileWriter fw = null;
		StringBuffer buffer = new StringBuffer();
		String message = null;
		String historyErrQueueName = loadHistoryConfig.getHistoryErrQueueName();
		List<String> exportQueueMessageList = new ArrayList<String>();
		int exportCnt = 0;
		try {
			fw = new FileWriter(file);
			while (true) {

				message = rabbitmqManager.recieveMessage(historyErrQueueName);

				if (message == null) {
					logger.info("export[" + exportCnt + "]queues successful");
					break;
				}

				buffer.setLength(0);
				buffer.append(message).append(END_PIXEL);
				fw.write(buffer.toString());

				exportQueueMessageList.add(message);
				exportCnt++;
			}
			for (String exportedMessage : exportQueueMessageList) {
				rabbitmqManager
						.setMessage(historyErrQueueName, exportedMessage);
			}
			logger.info("rePut[" + exportCnt + "]queues successful");
			logger.info(System.getProperty("log4jRoot"));
			return "export [" + exportCnt + "]queues successful to file["
					+ fileName + "]";

		} catch (Exception ex) {
			ex.printStackTrace();
			logger.error(ex.toString());
		} finally {
			if (fw != null) {
				try {
					fw.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return "export failed,view detail error message in the error.log of log4j";
	}

	public static void main(String[] args) throws Exception {
		ApplicationContext ctx = new ClassPathXmlApplicationContext(
				new String[] { 
						"applicationContext-rabbitmq.xml",
						"applicationContext-service.xml",
						"applicationContext.xml" });
		LoadMainService loadErrorMainService = (LoadMainService) ctx
				.getBean("loadErrorMainService");
		loadErrorMainService.setHisQueueName("HIS_RET_PRD_INFO");
		loadErrorMainService.setHisErrorQueueName("HIS_RET_PRD_INFO.ERR");
		loadErrorMainService.SubMainProc("<transaction><trans_cnt>1</trans_cnt><table><ac_recipe_id/><act_cmp_timestamp/><act_stb_timestamp>2015-03-25 00:46:00.0</act_stb_timestamp><batch_no/><bnk_flg>0</bnk_flg><box_id_fk/><c_rubbing_time>9</c_rubbing_time><cost_code/><cr_ope_id_fk>JB-10</cr_ope_id_fk><cr_ope_no_fk>JB-10</cr_ope_no_fk><cr_ope_ver_fk>00000</cr_ope_ver_fk><cr_path_id_fk>JBDM0001</cr_path_id_fk><cr_path_ver_fk>00000</cr_path_ver_fk><cr_proc_id_fk>JBQA</cr_proc_id_fk><cr_tool_id_fk>JB-4F-OQC-001</cr_tool_id_fk><cr_toolg_id_fk>G_JB10</cr_toolg_id_fk><cus_sn>11111111100000000000000000000000000000000000000000</cus_sn><def_code1/><def_code1_cnt/><def_code1_lc/><def_code1_sd/><def_code2/><def_code2_cnt/><def_code2_lc/><def_code2_sd/><def_code3/><def_code3_cnt/><def_code3_lc/><def_code3_sd/><def_code4/><def_code4_cnt/><def_code4_lc/><def_code4_sd/><def_code5/><def_code5_cnt/><def_code5_lc/><def_code5_sd/><dest_shop/><dn_no/><dps_id_fk/><ds_recipe_id/><evt_cate>PSTR</evt_cate><evt_dept/><evt_seq_id>EE7UGLMBVXSCYF8R6BDY40TCV</evt_seq_id><evt_time_d>42090.3775174537</evt_time_d><evt_timestamp>2015-03-27 09:03:37.0</evt_timestamp><evt_usr>05317</evt_usr><fab_id/><fab_sn>153090050206</fab_sn><fst_dps_id_fk/><fst_iqc_batch_id/><fst_judge_timestamp>2015-03-26 07:31:24.0</fst_judge_timestamp><fst_judge_tool_id>WG-PG-0077</fst_judge_tool_id><fst_logof_timestamp/><fst_logon_timestamp>2015-03-25 00:46:00.0</fst_logon_timestamp><fst_lot_id_fk/><fth_dps_id_fk/><fth_lot_id_fk/><group_id/><jge_ope_no_fk/><layot_id_fk>8*5_S</layot_id_fk><line_id/><logof_timestamp>2015-03-26 16:37:45.0</logof_timestamp><logof_usr>02735</logof_usr><logon_timestamp>2015-03-27 09:03:33.0</logon_timestamp><logon_usr>05317</logon_usr><lot_id>T21503240040R015</lot_id><lot_splt_id>00</lot_splt_id><mdl_cate_fk>AB</mdl_cate_fk><mdl_id_fk>C5550G270</mdl_id_fk><mdl_typ_fk>699*575</mdl_typ_fk><mtrl_box_id_fk>15309005M002</mtrl_box_id_fk><mtrl_grade_fk/><mtrl_lot_id_fk/><mtrl_pallet_id_fk/><mtrl_prod_id_fk>TM055JYSP34-20</mtrl_prod_id_fk><mtrl_slot_no_fk/><nx_ope_id_fk>JB-11</nx_ope_id_fk><nx_ope_no_fk>JB-11</nx_ope_no_fk><nx_ope_ver_fk>00000</nx_ope_ver_fk><nx_path_id_fk>JBDM0001</nx_path_id_fk><nx_path_ver_fk>00000</nx_path_ver_fk><nx_proc_id_fk>JBPK</nx_proc_id_fk><nx_tool_id_fk/><nx_toolg_id_fk>G_JB11</nx_toolg_id_fk><ope_evt_name>XpstartprocService</ope_evt_name><ope_evt_no>HXTFZMYVD8VQRZ67MK2LAII1</ope_evt_no><ope_evt_node>192.168.2.245</ope_evt_node><ope_evt_usr>WG</ope_evt_usr><ope_tbl_name>RET_PRD_INFO</ope_tbl_name><operation>IorUAL</operation><oqc_lotid/><oqc_skip_flg/><p1_timestamp>2015-03-27 09:03:37.0</p1_timestamp><p2_timestamp/><p3_timestamp/><p4_timestamp>2015-03-26 16:34:48.0</p4_timestamp><p5_timestamp/><p6_timestamp/><pallet_id/><prd_admin_flg>NNNNNNNNNNNNNNNNNNNN</prd_admin_flg><prd_grade/><prd_qty>40</prd_qty><prd_seq_id>153090050206</prd_seq_id><prd_seq_typ>S</prd_seq_typ><prd_stat>INPR</prd_stat><prd_std_qty>40</prd_std_qty><prd_swh_cnt/><prd_thickness>0.4</prd_thickness><prd_total_swh_cnt/><proc_cnt/><proc_flg>Y</proc_flg><prty/><pv_box_id_fk>15311030M004</pv_box_id_fk><pv_evt_timestamp/><pv_evt_usr/><pv_logof_timestamp>2015-03-26 07:31:25.0</pv_logof_timestamp><pv_logof_usr>02386</pv_logof_usr><pv_logon_timestamp>2015-03-26 08:02:45.0</pv_logon_timestamp><pv_logon_usr>04933</pv_logon_usr><pv_prd_grade>OK</pv_prd_grade><pv_prd_seq_id/><pv_prd_stat_fk>WAIT</pv_prd_stat_fk><pv_prd_thickness>0.0</pv_prd_thickness><pv_proc_id_fk/><pv_prty/><pv_slot_no/><pv_tool_id_fk/><pv_toolg_id_fk/><pv_unq_seq_id>8KJ6BM8DV7HPA4OY6M4RXLF4N</pv_unq_seq_id><pv_wo_id_fk/><qrs_ovr_flg>N</qrs_ovr_flg><relate_usr/><rma_no/><rsn_cate1/><rsn_cate2/><rsn_cate3/><rsn_cate4/><rsn_cate5/><rsn_code1/><rsn_code2/><rsn_code3/><rsn_code4/><rsn_code5/><rsn_dept1/><rsn_dept2/><rsn_dept3/><rsn_dept4/><rsn_dept5/><rsn_lc1/><rsn_lc2/><rsn_lc3/><rsn_lc4/><rsn_lc5/><rsv_no/><rubbing_typ/><sequence/><ship_box_id_fk/><shipping_timestamp/><sht_ope_msg/><slot_no>2</slot_no><snd_dps_id_fk/><snd_iqc_batch_id/><snd_judge_timestamp>2015-03-26 07:31:24.0</snd_judge_timestamp><snd_judge_tool_id>WG-PG-0077</snd_judge_tool_id><snd_lot_id_fk/><so_id_fk>DQR20150366</so_id_fk><sta_time_d>42090.377517939814</sta_time_d><sv_ope_id_fk/><sv_ope_no_fk/><sv_ope_ver_fk/><sv_path_id_fk/><sv_path_ver_fk/><t_rubbing_time>7</t_rubbing_time><tool_id_fk>JB-4F-OQC-001</tool_id_fk><tool_port_id_fk/><trd_dps_id_fk/><trd_iqc_batch_id/><trd_lot_id_fk/><unq_seq_id>1JO43MFPPT2F22LSYN4BJUTPI</unq_seq_id><wh_in_timestamp/><wo_id_fk>YJD605567</wo_id_fk><x_axis_cnt_fk>8</x_axis_cnt_fk><y_axis_cnt_fk>5</y_axis_cnt_fk></table></transaction>");
		
	}
}
